<?php
/**
 * Dump everything here first...
 */

function get_description() {
	global $options;
	
	if (!empty($options['description']))
		print('
			<div id="description">
				'.wpautop($options['description']).'
			</div>
		');
}

function dashboard() {
	$url = get_bloginfo('url');
	echo '<a href="'.$url.'/wp-admin/" id="dashboard" title="Go to Dashboard">Dashboard</a>';
}

if (is_user_logged_in())
	add_action('wp_footer', 'dashboard');

function get_menu() {
	global $options;
	
	if ($options['menu'] == '1') {
		echo '<ul id="menu">';
		$menu = wp_list_pages('title_li=&sort_column=menu_order&echo=0'); // Params for the page list in header.php
		echo str_replace(array("\r", "\n", "\t"), '', $menu);
		echo "</ul>\n";
	}
}

/**
 * Better excerpt for search results
 */
function trim_excerpt($text) {
	global $options, $post;
	
	if ('' == $text) {
		$text = get_the_content('');
		$text = apply_filters('the_content', $text);
		$text = str_replace(']]>', ']]&gt;', $text);
	
		if (!in_category($options['link'])) 
			$text = strip_tags($text);
	
		$excerpt_length = 55;    
		$words = explode(' ', $text, $excerpt_length + 1);
	
		if (count($words) > $excerpt_length) {
			array_pop($words);
			array_push($words, '[...]');
			$text = implode(' ', $words);
		} elseif (count($words) <= 1) {
			$text = strlen($post->post_title) ? wptexturize($post->post_title) : sprintf('Post #%s [...]', $post->ID);
		}
	}
	
	return $text;
}

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'trim_excerpt');

/**
 * Hook text type category to Write Post if set
 */
function add_text_category() {
	global $options;
	
	if ($options['text'] != '0' && !strpos($_SERVER['REQUEST_URI'], 'post.php'))
		echo '<input type="hidden" name="post_category[]" value="'.$options['text'].'" />';
}

add_action('edit_form_advanced', 'add_text_category');

/**
 * Remove Write Post, Write Page menu then redirect to our custom page
 */
function _redirect() {
	global $options, $submenu;
	
	if ($options['text'] == '0')
		unset($submenu['post-new.php'][5]); // Write Post
		
	unset($submenu['post-new.php'][10]); // Write Page

	$url = $_SERVER['REQUEST_URI'];
	
	if (preg_match('#admin.php\?page=#', $url)) {
		$new = preg_replace('#admin.php\?page=.*?#', 'post-new.php?page=\1', $url);
		wp_redirect($new);
		exit();
	}
}

if (!current_user_can('manage_options')) {
	add_action('admin_head', '_redirect');
}

/**
 * Loads custom Write and Options CSS and Quicktags config 
 */
function _scripts() {
	$template_url = get_bloginfo('template_url');
	
	if (strpos($_SERVER['REQUEST_URI'], 'post-new.php?page=')) {
		echo '<link rel="stylesheet" href="'.$template_url.'/css/post.css" type="text/css" />';
	}
	
	if (strpos($_SERVER['REQUEST_URI'], 'themes.php?page=')) {
		echo '<link rel="stylesheet" href="'.$template_url.'/css/options.css" type="text/css" />';
	}
	
	if (strpos($_SERVER['REQUEST_URI'], 'post-new.php?page=') || strpos($_SERVER['REQUEST_URI'], 'themes.php?page=')) {
		wp_print_scripts('quicktags');
		echo '<script src="'.$template_url.'/js/quicktags.config.js" type="text/javascript"></script>';
	}
}

add_action('admin_head', '_scripts');

function meta_description() {
// Kaf Oseo, Head META Description
    global $wp_query;
    $length = 20;
    
    if (is_single() || is_page() ) {
        $post = $wp_query->post;
        
        if (!empty($post->post_excerpt)) {
            $text = $post->post_excerpt;
        } else {
            $text = $post->post_content;
        }
        
        $text = str_replace(array("\r\n", "\r", "\n", "\t"), " ", $text);
        $text = str_replace(array("\""), "", $text);
        $text = trim(strip_tags($text));
        $text = explode(' ', $text);
        
        if (count($text) > $length) {
            $ellipsis = '...';
        } else {
            $length = count($text);
            $ellipsis = '';
        }
        
        $description = '';
        
        for ($i = 0; $i<$length; $i++) {
			if ($i != 0) {
				$description .= " ";
			}
			
            $description .= $text[$i];
		}
		
        $description .= $ellipsis;
        
    } elseif (is_category()) {
        $category = $wp_query->get_queried_object();
        $description = trim(strip_tags($category->category_description));
    } else {
        $description = trim(strip_tags(get_bloginfo('description')));
    }

    if ($description) {
        echo '<meta name="description" content="'.$description.'" />';
    }
}

if (!function_exists('head_meta_desc'))
	add_action('wp_head', 'meta_description'); 

function body_class($print = true) {
// Andy Skelton and Scott Wallick, Sandbox theme
	$c = array('hfeed');

	is_home()       ? $c[] = 'home'       : null;
	is_archive()    ? $c[] = 'archive'    : null;
	is_date()       ? $c[] = 'date'       : null;
	is_search()     ? $c[] = 'search'     : null;
	is_paged()      ? $c[] = 'paged'      : null;
	is_attachment() ? $c[] = 'attachment' : null;
	is_404()        ? $c[] = 'four04'     : null;

	if (is_user_logged_in())
		$c[] = 'loggedin';
		
	$c = join(' ', apply_filters('body_class',  $c));
	
	return $print ? print($c) : $c;
}

function post_class($print = true) {
	global $types, $options;
	
	$c = array('hentry');

	if (!is_page()) {
		foreach ($types as $type):
			switch (true):
				case in_category($options[$type]):
					$c[] = $type;
					break;
			endswitch;
		endforeach;

		if (in_category($options['link']))
			$c[] = 'xfolkentry';
	}	
		
	$c = join(' ', apply_filters('post_class', $c));

	return $print ? print($c) : $c;		
}

function format_post($content) {
	global $options;
	
	switch (true):
		//case in_category($options['text']):
		//	break;
			
		case in_category($options['photo']):
			$content = preg_replace(array('|\r|', '|\n|', '|\t|'), '', $content); 			
			$a = '#<p><img(.*?)alt="(.*?)" /></p>#s';
			$b = '<img class="figure"\1alt="IMAGE: \2" /> ';	
			$c = '#<p><a(.*?)href="([^"]*.)"(.*?)><img(.*?)alt="(.*?)" /></a></p>#s';
			$d = '<a\1href="\2"\3><img class="figure"\4alt="IMAGE: \5" /></a> ';
			$content = preg_replace(array($a, $c), array($b, $d), $content);				
			$content = preg_replace_callback('#(<p>.*?</p>)+#', _caption, $content);
			break;
			
		case in_category($options['quote']):
		case in_category($options['text']):
			$content = preg_replace(array('|\r|', '|\n|', '|\t|'), '', $content); 
			$content = preg_replace('#<blockquote([^>]*)><p>(.*?)</blockquote>#s', '<blockquote\1><p><span class="ldquo">&ldquo;</span>\2</blockquote>', $content);
			$content = preg_replace('#<p>\&mdash; (?:<cite>|)(.*?)(?:</cite>|)</p>#s', ' <p class="source">&mdash; <cite>\1</cite></p>', $content);
			break;
			
		case (in_category($options['link'])):
			$content = preg_replace(array('|\r|', '|\n|', '|\t|'), '', $content); 
			
			if (!is_feed()) {
				$content = preg_replace('#<p><a(.*?)href="([^"]*.)"(.*?)>(.*?)</a><\/p>#s', '<span class="raquo">&raquo;</span> <a rel="bookmark nofollow" class="taggedlink"\1href="\2"\3>\4</a>', $content);
			} else {
				$content = preg_replace('#<p><a(.*?)href="([^"]*.)"(.*?)>(.*?)</a><\/p>#s', '', $content);
			}
			
			$content = preg_replace_callback('#(<p>.*?</p>)+#', _caption, $content);
			break;
			
		case in_category($options['chat']):
			$content = preg_replace(array('|<p>|', '|</p>|', '|<br />|'), '', $content);
			$lines = explode("\n", $content);			
			$i = 1;
			$chat .= '<ol>';
			foreach ($lines as $line) {
				if ($line != '') {
					$class = ($i % 2) ? 'odd' : 'even';
					$line = wp_specialchars($line);
					
					$text = preg_replace('#^(\w+): ([^>]*)#s', '<cite>\1</cite>: <blockquote>\2</blockquote>', $line);
					$text = preg_replace('#&lt;(.*?)&gt; ([^>]*)#s', '<cite>&lt;\1&gt;</cite> <blockquote>\2</blockquote>', $text);
					
					if ($line == $text)
						$text = '<blockquote>'.$line.'</blockquote>';
					
					$chat .= '<li class="'.$class.'">'.$text.'</li>';
					$i++;
				}
			}
			$chat .= '</ol>';		
			return $chat;
			break;
			
		case (in_category($options['video']) && !is_feed()):
			$content = preg_replace(array('|\r|', '|\n|', '|\t|'), '', $content); 
			$a = '#<p><object[^>]+>.+?value="(http://[a-zA-Z0-9\._-]+\.[a-zA-Z]+\/?[a-zA-Z0-9\/\._\-\?\=\&\;]*)".+?</object></p>#s';
			$b = '#<p><embed[^>]+.+?src="(http://[a-zA-Z0-9\._-]+\.[a-zA-Z]+\/?[a-zA-Z0-9\/\._\-\?\=\&\;]*)".+?</embed></p>#s';
			$c = '#<p><embed src="(http://[a-zA-Z0-9\._-]+\.[a-zA-Z]+\/?[a-zA-Z0-9\/\._\-\?\=\&\;]*)".+</embed></p>#s';
			$d = '<object width="425" height="355" type="application/x-shockwave-flash" data="\1"><param name="movie" value="\1" />VIDEO: <a href="\1">\1</a></object> ';
			$content = preg_replace(array($a, $b, $c), $d, $content);
			$content = preg_replace_callback('#(<p>.*?</p>)+#', _caption, $content);			
			break;
	endswitch;
	
	return $content;
}

function _caption($content) {
	global $options;	

	if (!in_category($options['link']))
		$class = 'caption'; 
	else
		$class = 'description';
	
	return '<div class="'.$class.'">'.$content[0].'</div>';
}

add_filter('the_content', 'format_post');

function format_rss_link($permalink) {
	global $options;

	if (in_category($options['link'])) {
		$content = get_the_content();
		$permalink = preg_replace('#<a(.*?)href="([^"]*.)"(.*?)>[^>]+</a>(?:[^>]+|)#s', '\2' , $content);
	}

	return $permalink;
}

add_filter('the_permalink_rss', 'format_rss_link');

/**
 * Custom Page and Post Navigation
 */
function page_navigation() {
	global $wp_query, $paged;

	if (!is_single()) {
		$max_page = $wp_query->max_num_pages;
		
		if (empty($paged))
			$paged = 1;

		if ($max_page >= 1) { 
			echo "<div id=\"navigation\">";
			if ($paged != $max_page) {
				echo "<span class=\"next\">&larr; ";
					next_posts_link('Older');
				echo "</span>";
			}
				
			echo "\t<span class=\"current\">Page $paged of $max_page</span>\t";
			
			if ($paged != 1) {
				echo "<span class=\"previous\">";
					previous_posts_link('Newer');
				echo " &rarr;</span>";
			}

			echo "</div>";
		}
		
	} else {
		$previous = get_previous_post();
		$next = get_next_post();
		
		if ($previous || $next) {
			echo "<div id=\"navigation\">";

				if ($previous) {
					echo "<span class=\"next\">&larr; ";
						previous_post_link('%link', 'Previous');
					echo "</span>\t";
				} 
		
				if ($next) {
					echo "\t<span class=\"previous\">";
						next_post_link('%link', 'Next');
					echo " &rarr;</span>";
				}

			echo "</div>";
		}
	}
}	

/**
 * Convert an array of strings to upper case words
 * http://www.php.net/ucwords
 */
function _capitalize($input) {
	if (is_array($input)) {
		foreach ($input as $value) {
			$value = _capitalize($value);
	}
	return $input;
   
	} else if (is_string($input)) {
		return ucwords(strtolower($input));
	} else {
		return $input;
	}
}

/**
 * Pedro Santana, gelato CMS modified file_get_contents() from: 
 * http://work.dokoku.net/Anieto2k/_file_get_contents.phps
 */
function _file_get_contents($path) {
	if (!preg_match('/^http/i', $path)) {
		if ($fp = fopen($path, 'r')) {
			return fread($fp, 1024);
		} else {			
			return false;
		}
	} else {
		if (extension_loaded('curl') && version_compare(get_curl_version(), '7.10.5', '>=')) {
			$ch = curl_init();
			$timeout = 5;
			curl_setopt ($ch, CURLOPT_URL, $path);
			curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$file_contents = curl_exec($ch);
			curl_close($ch);
			if (is_string($file_contents)) {
				return $file_contents;
			} else {
				return false;
			}
		} else {
			$data = parse_url($path);
			if (!$data['host'] || $data['scheme'] != "http") {
				return false;
			}
	
			$f = @fsockopen($data['host'], ($data['port']) ? $data['port'] : 80, $e1, $e2, 3);
			if (!$f) {
				return false;
			}

			$url = get_bloginfo('url');
			$q = "GET " . $data['path'] . (isset($data['query'])?'?'.$data['query']:'') . " HTTP/1.1\r\n";
			$q .= "Host: " . $data['host'] . "\r\n";
			$q .= "Connection: close\r\n";
			$q .= "Referer: " . $url . "\r\n\r\n";
	
			$recv = "";
			fwrite($f, $q);
			while (!feof($f)) {
				$recv .= fread($f, 1024);
			}
	
			$request = $q;
			$response = substr($recv, 0, strpos($recv, "\r\n\r\n"));
			$body = substr($recv, strpos($recv, "\r\n\r\n") + 4);
	
			if (preg_match('/http\/1\\.[0|1] ([0-9]{3})/i', $response, $res)) {
				if ($res[1][0] != "2") {
					return false;
				}
			} else {
				return false;
			}
	
			if (preg_match('/transfer-encoding:\s*chunked/i', $response)) {
				$tmp_body = $body;
				$new = "";
				$exit = false;
				while (!$exit) {
					if (preg_match('/^([0-9a-f]+).*?\r\n/i', $tmp_body, $res)) {
						$len = hexdec($res[1]);
						if ($len == "0") {
							$exit = true;
							break;
						}
						$new .= substr($tmp_body, strlen($res[0]), $len);
						$tmp_body = substr($tmp_body, strlen($res[0]) + $len + strlen("\r\n"));
					} else {
						$exit = true;
					}
				}
				$body = $new;
			}	
			return $body;
		}
	}
}

function get_curl_version() {
	$curl = 0;
	if (is_array(curl_version())) {
		$curl = curl_version();
		$curl = $curl['version'];
	} else {
		$curl = curl_version();
		$curl = explode(' ', $curl);
		$curl = explode('/', $curl[0]);
		$curl = $curl[1];
	}
	return $curl;
}

?>